<template>
  <div class="footer">
    <div class="song-info">
      <div :class="['song-cover', songCoverAnimate]" @click="openSongDetail">
        <img
          v-if="isCoverErr"
          style="width: 76%;height: 76%"
          src="@/assets/images/music.png"
          alt=""
        />
        <img
          v-else
          :src="currentSong && currentSong.picUrl ? currentSong.picUrl : ''"
          @error="isCoverErr = true"
          @load="isCoverErr = false"
        />
      </div>
      <div class="song-msg">
        <a-tooltip>
          <template slot="title">
            {{ currentSong && currentSong.name ? currentSong.name : "" }}
          </template>
          <span class="song-title">{{
            currentSong && currentSong.name ? currentSong.name : ""
          }}</span>
        </a-tooltip>
        <a-tooltip>
          <template slot="title">
            {{ currentSong | returnSinger }}
          </template>
          <span class="song-singer">{{ currentSong | returnSinger }}</span>
        </a-tooltip>
      </div>
    </div>
    <div class="song-control">
      <div class="song-btn">
        <a-tooltip>
          <template slot="title">
            上一首
          </template>
          <i
            class="iconfont icon-shangyishouge"
            @click="onChangSong('prev')"
          ></i>
        </a-tooltip>
        <a-tooltip>
          <template slot="title">
            播放/暂停
          </template>
          <i
            :class="[
              'iconfont player',
              playStatus ? 'icon-zanting' : 'icon-bofang',
            ]"
            @click="setPlay"
          ></i>
        </a-tooltip>
        <a-tooltip>
          <template slot="title">
            下一首
          </template>
          <i class="iconfont icon-xiayishou" @click="onChangSong('next')"></i>
        </a-tooltip>
      </div>
      <div class="song-progress">
        <span class="time">{{ durationTrans(songStartTime) }}</span>
        <a-slider
          v-model="progressVal"
          :default-value="0"
          :tooltipVisible="false"
          @change="progressChange"
        />
        <span class="time">{{
          durationTrans(currentSong && currentSong.time ? currentSong.time : 0)
        }}</span>
      </div>
    </div>
    <div class="song-set">
      <!-- 播放方式 -->
      <a-tooltip>
        <template slot="title">
          {{ playModeText[playMode].text }}
        </template>
        <i
          :class="'iconfont ' + playModeText[playMode].icon"
          @click="setPlayMode()"
        ></i>
      </a-tooltip>

      <!-- 音量调节 -->
      <div class="volume">
        <i :class="['iconfont', volumeIcon]" @click="handleVolume"></i>
        <a-slider
          v-model="initVolume"
          :default-value="volume"
          @change="volumeChange"
        />
      </div>
      <!-- 播放列表 -->
      <i class="iconfont icon-gedan" @click="setDrawList()"></i>
    </div>

    <!-- 音乐标签 -->
    <audio
      style="display: none"
      controls
      ref="audioRef"
      :src="currentSong && currentSong.url ? currentSong.url : ''"
    ></audio>
  </div>
</template>

<script>
import { getSongUrl } from "@/apis/audio";
import { mapMutations, mapState, mapActions } from "vuex";
import { durationTrans } from "@/utils/util";
import { returnSinger } from "@/utils/filter";
import { playMode, playModeText, playModeList } from "@/common/cantas";

export default {
  name: "SongBar",
  components: {},
  props: {},
  data() {
    return {
      isCoverErr: false,
      playModeText: playModeText,
      songStartTime: 0,
      songEndTime: 0,
      isMute: false,
      initVolume: 50,
      songCoverAnimate: "shadow-drop-2-lr",
      audioInstance: null,
      timer: null,
      progressVal: 0,
    };
  },
  computed: {
    ...mapState(["volume", "electronStore", "playStatus"]),
    currentPlaylistIndex() {
      return this.$store.state.electronStore.currentPlaylistIndex;
    },
    currentSong() {
      return this.$store.state.electronStore.currentSong;
    },
    playMode() {
      return this.electronStore.playMode;
    },
    playList() {
      return this.electronStore.playList;
    },
    volumeIcon() {
      return this.volume === 0
        ? "icon-guanbishengyin"
        : this.volume === 100
        ? "icon-zuidayinliang"
        : "icon-yinliang";
    },
  },
  watch: {
    "currentSong.id": {
      immediate: false,
      handler: function(newval) {
        console.log(newval, "watch,当前播放id");
        if (newval) this.getSongUrl(newval);
      },
    },
  },
  created() {
    this.initVolume = this.volume;
  },
  mounted() {
    this.isCoverErr = false;
    this.setPlayStatus(false);
    // 播放时间改变
    if (this.$refs.audioRef.src) {
      this.$refs.audioRef.volume = this.initVolume / 100;
      this.$refs.audioRef;
      this.$refs.audioRef.addEventListener(
        "timeupdate",
        this.$_.throttle((e) => {
          this.songStartTime = this.$refs.audioRef.currentTime * 1000;
          const time = Math.ceil(
            (Number(this.songStartTime) / Number(this.currentSong.time)) * 100
          );
          this.progressVal = !time
            ? 0
            : time >= 100
            ? 100
            : time < 1
            ? 0
            : time;
        }, 500)
      );

      // this.$refs.audioRef.addEventListener("error", (e) => {
      //   console.log(e, "error");
      //   this.$message.error("歌曲加载错误！");
      //   this.setPlayStatus(false);
      // });
      this.$refs.audioRef.addEventListener("ended", () => {
        console.log("播放结束");
        // 判断播放方式
        if (this.playMode === playMode.listPlay) {
          // 列表
          if (this.currentPlaylistIndex >= this.playList.length - 1) {
            this.setPlayStatus(false);
          } else {
            this.onChangSong("next");
          }
        } else if (this.playMode === playMode.loopPlay) {
          // 循环
          if (this.currentPlaylistIndex >= this.playList.length - 1) {
            this.setCurrentPlaylistIndex(0);
            this.setCurrentSong({
              isEmpty: true,
              value: this.playList[this.currentPlaylistIndex],
            });
          } else {
            this.onChangSong("next");
          }
        } else if (this.playMode === playMode.singleCycle) {
          // 单曲
          this.$refs.audioRef.play();
        }
      });
    }
  },
  beforeDestroy() {
    if (this.$refs.audioRef) {
      this.$refs.audioRef.removeEventListener("timeupdate", () => {});
      this.$refs.audioRef.removeEventListener("ended", () => {});
      // this.$refs.audioRef.removeEventListener("error", () => {});
    }
  },
  methods: {
    durationTrans,
    ...mapMutations([
      "setDrawList",
      "setPlayMode",
      "setPlayStatus",
      "setCurrentPlaylistIndex",
      "setVolume",
      "setCurrentSong",
    ]),
    // 播放按钮
    async setPlay() {
      console.log(this.currentSong.url, "this.currentSong.url");
      if (!this.$refs.audioRef.src || !this.currentSong.url) {
        await this.getSongUrl(this.currentSong.id);
      }
      await this.$nextTick(async () => {
        if (!this.currentSong.url) return this.$message("无法获取播放地址！");
        this.$refs.audioRef.paused
          ? this.$refs.audioRef.play()
          : this.$refs.audioRef.pause();
        this.setPlayStatus();
      });
    },
    // 歌曲切换
    onChangSong(direction) {
      console.log(this.playList.length, this.currentPlaylistIndex, "direction");
      if (this.currentPlaylistIndex >= this.playList.length - 1) {
        this.setPlayStatus(false);
        return this.$message.warning("已经到底了~！");
      }
      if (this.currentPlaylistIndex <= 0 && direction === "prev") {
        this.setPlayStatus(false);
        return this.$message.warning("已经到头了~！");
      }
      this.setCurrentPlaylistIndex(
        this.currentPlaylistIndex + (direction === "next" ? +1 : -1)
      );
      this.setCurrentSong({
        isEmpty: true,
        value: this.playList[this.currentPlaylistIndex],
      });
    },
    // 歌曲进度
    progressChange(value) {
      if (this.$refs.audioRef)
        this.$refs.audioRef.currentTime =
          ((value / 100) * this.currentSong.time) / 1000;
    },
    // 音量调节
    volumeChange(value) {
      this.setVolume(value);
      this.initVolume = value;
      if (this.$refs.audioRef) this.$refs.audioRef.volume = value / 100;
    },
    // 音量按钮
    handleVolume() {
      if (this.isMute) {
        const half = 50;
        this.setVolume(half);
        this.initVolume = half;
        if (this.$refs.audioRef) this.$refs.audioRef.volume = half / 100;
      } else {
        const zero = 0;
        this.setVolume(zero);
        this.initVolume = zero;
        if (this.$refs.audioRef) this.$refs.audioRef.volume = zero;
      }
      this.isMute = !this.isMute;
    },
    // 歌曲详情
    openSongDetail() {
      this.songCoverAnimate = "";
      setTimeout(() => {
        this.songCoverAnimate = "shadow-drop-2-lr";
      }, 200);
    },
    // 获取歌曲url
    getSongUrl(id) {
      // 在此可能需要判断是否为本地路径
      return getSongUrl(id)
        .then((res) => {
          const { code, data } = res;
          if (code === 200 && data[0].code === 200) {
            this.setCurrentSong({
              value: { url: data[0].url, isLocal: false },
              isEmpty: false,
            });
            return true;
          } else {
            throw data[0].code;
          }
        })
        .catch((err) => {
          this.$message.error(
            [404, 403, 401].includes(err) ? "找不到该歌曲或未登录" : "获取异常"
          );
          this.setPlayStatus(false);
          return false;
        });
    },
  },
  filters: {
    returnSinger,
  },
};
</script>

<style lang="less">
.popover-playlist {
  .ant-popover-inner-content {
    height: 320px;
    overflow: auto;
    .hide-scrpllbar;
  }
}
</style>
<style lang="less" scoped>
@import "./index.less";
</style>
